package com.aorise.service.assess.impl;

import com.aorise.exception.ServiceException;
import com.aorise.mapper.assess.AssessMapper;
import com.aorise.mapper.camera.CameraMapper;
import com.aorise.mapper.system.SysConfigMapper;
import com.aorise.model.assess.AssessModel;
import com.aorise.model.system.SysConfigModel;
import com.aorise.service.assess.AssessService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.excel.ExcelUtil;
import com.aorise.utils.page.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:cat
 * @Desicription: 考核信息接口服务实现类
 * @Date:Created in 2019-06-20
 * @Modified By:
 */
@Service
public class AssessServiceImpl implements AssessService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AssessMapper assessMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private CameraMapper cameraMapper;

    /**
     * @Author:cat
     * @Description 分页查询考核信息
     * @params: map 查询条件
     * @params: page 分页
     * @Date:2019-06-20
     * @Return: List<AssessModel> 考核信息集合
     * @Modified By:
     */
    @Override
    public List<AssessModel> getAllAssessListByPage(Map<String, Object> map, Page page) {
        List<AssessModel> assessModels = null;

        /**查询总条数*/
        Long count = assessMapper.getAllAssessListTotalByPage(map);
        if (count > 0) {
            page.setTotalCount(count);
            page.setTotalPage(count, page.getEveryPage());
            if (page.getCurrentPage() > 0 && page.getEveryPage() > 0) {
                /**查询分页条数*/
                assessModels = assessMapper.getAllAssessListByPage(map);
            }
        } else {
            page.setTotalCount(0L);
        }
        return assessModels;
    }

    /**
     * @Author:cat
     * @Description 统计前一天的考核管理信息
     * @Date:2019-06-20
     * @Return: Integer 主键
     * @Modified By:
     */
    @Override
    public Integer updateAssess() {
        Map<String, Object> map;

        /**前一天日期*/
        String assessDate = getYesterdayByCalendar();

        map = new HashMap<>();
        map.put("assessDate", assessDate);
        AssessModel assess = assessMapper.getAssessByDate(map);
        int count =1;
        if(assess == null) {

            logger.info("我是考勤统计————————进来了"+count);
            AssessModel assessModel = new AssessModel();

            /**考核日期*/
            assessModel.setAssessDate(assessDate);

            /**应接入数*/
            map = new HashMap<>();
            map.put("conType", ConstDefine.SYSCONFIG_TYPE_2);
            map.put("state", ConstDefine.STATE_ABLE);

            List<SysConfigModel> sysConfigModels = sysConfigMapper.getSysConfig(map);
            if (sysConfigModels.size() == 0) {
                logger.error("缺少应接入数配置");
                throw new ServiceException("缺少应接入数配置");
            }
            assessModel.setAccess(Integer.parseInt(sysConfigModels.get(0).getConValue()));

            /**实际接入数*/
            map = new HashMap<>();
            map.put("halt", ConstDefine.HALT_NO);
            map.put("state", ConstDefine.STATE_ABLE);
            Integer caSum = cameraMapper.getCameraTotal(map);
            assessModel.setRealAccess(caSum);

            /**接入率*/
            Integer accessRate = (int)((float)caSum / Integer.parseInt(sysConfigModels.get(0).getConValue())*100);
            assessModel.setAccessRate(accessRate);

            /**设备总数*/
            assessModel.setCaSum(caSum);

            /**设备在线数*/
            map = new HashMap<>();
            map.put("halt", ConstDefine.HALT_NO);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("online", ConstDefine.CAMERA_ONLINE);
            Integer caOnline = cameraMapper.getCameraTotal(map);
            assessModel.setCaOnline(caOnline);

            /**在线率*/
            Integer onlineRate = (int)((float)caOnline / caSum*100);
            assessModel.setOnlineRate(onlineRate);

            /**图像完好数*/
            map = new HashMap<>();
            map.put("conType", ConstDefine.SYSCONFIG_TYPE_3);
            map.put("state", ConstDefine.STATE_ABLE);
            List<SysConfigModel> sysConfigs = sysConfigMapper.getSysConfig(map);
            if (sysConfigs.size() == 0) {
                logger.error("缺少图像完好配置");
                throw new ServiceException("缺少图像完好配置");
            }
            String exception = "";
            for (int i = 0; i < sysConfigs.size(); i++) {
                if (sysConfigs.get(i).getConValue().equals(ConstDefine.SYS_CONFIG_CHECK_NO) ){
                    exception += (sysConfigs.get(i).getId() - 3) + ",";
                }
            }
            if (exception != "") {
                exception = exception.substring(0, exception.length() - 1);
            }

            map = new HashMap<>();
            map.put("halt", ConstDefine.HALT_NO);
            map.put("state", ConstDefine.STATE_ABLE);
            if(!StringUtils.isEmpty(exception))
                map.put("exception", "("+exception+")");
            Integer intact = cameraMapper.getCameraTotal(map);
            assessModel.setIntact(intact);

            /**图像完好率*/
            Integer intactRate = (int)((float)intact / caSum*100);
            assessModel.setIntactRate(intactRate);

            /**GIS采集数*/
            map = new HashMap<>();
            map.put("halt", ConstDefine.HALT_NO);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("gis", 1);
            Integer GIS = cameraMapper.getCameraTotal(map);
            assessModel.setGIS(GIS);

            /**GIS采集率*/
            Integer GISRate = (int)((float)GIS / caSum*100);
            assessModel.setGISRate(GISRate);

            /**得分*/
            Integer score = 100;
            assessModel.setScore(score);
            return assessMapper.addAssess(assessModel);
        }else {
            logger.error("前一天的考核管理信息已存在");
            return 0;
        }
    }

    /**
     * 获取前一天日期
     * @return
     */
    public String getYesterdayByCalendar(){
        Calendar calendar = Calendar.getInstance();
        System.out.println(Calendar.DATE);
        calendar.add(Calendar.DATE,-1);
        Date time = calendar.getTime();
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(time);
        return yesterday;
    }

    /**
     * @Author:cat
     * @Description 导出考核信息
     * @params: map 查询条件
     * @params: response
     * @Date:2019-06-20
     * @Modified By:
     */
    @Override
    public void exportAssess(Map<String, Object> map, HttpServletResponse response) {
        List<AssessModel> assessModels = assessMapper.exportAssess(map);
        if (assessModels.size() > 0) {

            List<String[]> list = new ArrayList<>();
            for (int i = 0; i < assessModels.size(); i++) {
                String arr[] = new String[12];
                arr[0] = assessModels.get(i).getAssessDate();
                arr[1] = assessModels.get(i).getAccess().toString();
                arr[2] = assessModels.get(i).getRealAccess().toString();
                arr[3] = assessModels.get(i).getAccessRate().toString()+"%";
                arr[4] = assessModels.get(i).getCaSum().toString();
                arr[5] = assessModels.get(i).getCaOnline().toString();
                arr[6] = assessModels.get(i).getOnlineRate().toString()+"%";
                arr[7] = assessModels.get(i).getIntact().toString();
                arr[8] = assessModels.get(i).getIntactRate().toString()+"%";
                arr[9] = assessModels.get(i).getGIS().toString();
                arr[10] = assessModels.get(i).getGISRate().toString()+"%";
                arr[11] = assessModels.get(i).getScore().toString();

                list.add(arr);
            }
            /**导出Excel*/
            ExcelUtil.writeExcel(list, null,12, 4, "考核信息","assess_list.xlsx", response);
        }
    }
}
